<?php
	require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'init.php');
	define("AKB_WL_LANG_FILE",		dirname(__FILE__).'/../includes/language/'.$GLOBALS['currentLanguage'].'/whitelabel.ini');
	define("AKB_LANG_FILE",			dirname(__FILE__).'/../includes/language/'.$GLOBALS['currentLanguage'].'/back_language.ini');
	define("AKB_LIB_PATH",			dirname(__FILE__).'/../lib/');
	define("AKB_TPL_LOAD_PATH",		dirname(__FILE__).'/templates/');
	define("AKB_TPL_PHP_PATH",		dirname(__FILE__).'/includes/display/');
	define('AKB_TPL_HTTP_PATH',		$GLOBALS['pathToKB'].'/admin/templates/');
	define('AKB_TPL_IMAGE_PATH',		AKB_TPL_HTTP_PATH.'Images');
	define("AKB_PANEL_LOAD_PATH",		AKB_TPL_LOAD_PATH.'Panels/');
	define("AKB_SNIPPET_LOAD_PATH",	AKB_TPL_LOAD_PATH.'Snippets/');
	define('CLASS_DIR',				dirname(__FILE__).'/includes/classes');

	require(AKB_LIB_PATH."/email.php");
	require_once(AKB_LIB_PATH."/multibyte.php");
	require(CLASS_DIR."/class.auth.php");
	require(CLASS_DIR."/class.template.php");
	require(CLASS_DIR."/class.admintable.php");
	require(CLASS_DIR."/class.question.php");
	require(CLASS_DIR."/class.helper.php");
	require(dirname(__FILE__)."/includes/helpers/helper.template.php");
	$GLOBALS['SNIPPETS'] = '';

	$GLOBALS["AKB_CLASS_TEMPLATE"]	= new AKB_TEMPLATE();
	$GLOBALS["AKB_CLASS_AUTH"]		= new AKB_AUTH();

	$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLResponseHeader');
	if (isset($_REQUEST['type'])) {
		switch ($_REQUEST['type']) {
			case 'saveVersion':
			if(!isset($_REQUEST['v'])) {
				exit;
			}

			$toSave = "<?php \$versionCache = array('latest' => '".$_REQUEST['v']."','lastCheck' => ".time()."); ?>";
			
			include_once(dirname(__FILE__).'/../lib/class.file.php');
			$path = dirname(__FILE__).'/tmp/LatestVersion.php';
			
			$f = new FileClass();
			if (is_file($path) && $f->CheckFileWritable($path)) {
				@include($path);
				$f->WriteToFile($toSave, $path);
				exit;
			}
			exit;				
			break;
			case 'questionlist':
				header('Content-type: text/xml');
				if (isset($_REQUEST['categoryid']) || $_REQUEST['categoryid']) {
					$query = "SELECT q.questionid, title
						FROM ".$GLOBALS['tablePrefix']."questions q, ".$GLOBALS['tablePrefix']."categoryassociations a
						WHERE q.questionid = a.questionid ";
					if (isset($_REQUEST['questionid']) && $_REQUEST['questionid'] != '') {	
						$query .= " AND q.questionid != '".$_REQUEST['questionid']."' ";
					}
					$query .= " AND a.categoryid = ".((int) $_REQUEST['categoryid']);
					$query .= ' AND (q.workflowstatus = \''.WF_STATUS_APPROVED.'\' OR q.workflowstatus = \''.WF_STATUS_AUTO_APPROVED.'\' OR q.workflowstatus = \''.WF_STATUS_REPENDING.'\' '.getShowDisapprovedArticleString('OR', 'q.').') ';
					$result = $GLOBALS['AKB_DB']->Query($query);
					while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
						$GLOBALS['ItemId'] = $row['questionid'];
						$GLOBALS['ItemText'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
						$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLResponseRow');
					}
					
					$GLOBALS['AKB_DB']->FreeResult($result);
				}
				break;
			case 'ldapgrouplist':
				header('Content-type: text/xml');
				$errorMessage = '';
				$results = array();
				
				if (!isset($_REQUEST['host']) || !$_REQUEST['host']) {
					$errorMessage .= GetLang('NoLdapHost');
				}
				elseif (!isset($_REQUEST['port']) || !$_REQUEST['port']) {
					$errorMessage .= GetLang('NoLdapPort');
				}
				elseif (!isset($_REQUEST['username']) || !$_REQUEST['username']) {
					$errorMessage .= GetLang('NoLdapConnectUsername');
				}
				elseif (!isset($_REQUEST['password']) || !$_REQUEST['password']) {
					$errorMessage .= GetLang('NoLdapConnectPassword');
				}
				elseif (!isset($_REQUEST['baseDn']) || !$_REQUEST['baseDn']) {
					$errorMessage .= GetLang('NoLdapBaseDn');
				}
				elseif (!isset($_REQUEST['ldapFollowReferral'])) {
					$errorMessage .= GetLang('NoLdapFollowReferral');
				}
				elseif (!isset($_REQUEST['ldapVersionThree'])) {
					$errorMessage .= GetLang('NoLdapVersionThree');
				}
				elseif (!isset($_REQUEST['ldapNegTLS'])) {
					$errorMessage .= GetLang('NoLdapNegTLS');
				}
				if ($errorMessage == '') {
					$groupFilterText = '(|(objectclass=group)(objectclass=groupOfUniqueNames)(objectclass=groupOfNames)(objectclass=posixGroup))';
					$ldapInstance = LdapFactory::initializeLdap($_REQUEST['ldapUserAccountType'], $_REQUEST['host'], $_REQUEST['port'], $_REQUEST['username'], $_REQUEST['password'], $_REQUEST['baseDn'],$_REQUEST['ldapVersionThree'],$_REQUEST['ldapNegTLS'],$_REQUEST['ldapFollowReferral'] );
					if (!$ldapInstance) {
						$errorMessage .= $ldapInstance->getErrorMsg();
					} else {
						if (!$ldapInstance -> bind()) {
							$errorMessage .= $ldapInstance->getErrorMsg();
						} else {
							 $results = $ldapInstance -> search($groupFilterText, array('cn', 'dn'), $_REQUEST['baseDn']);
							if (!is_array($results) || !sizeof($results)) {
								$errorMessage .= GetLang('NoLdapGroupFound');
							}
						}
					}
				}
				
				if (is_array($results) && $results && sizeof($results) && $errorMessage == '') {
					foreach ($results as $result) {
						$GLOBALS['ItemId'] = $result['dn'];
						//$GLOBALS['ItemText'] = htmlspecialchars($result['dn'], ENT_QUOTES, $GLOBALS['charset']);
						$GLOBALS['ItemText'] = htmlspecialchars("({$result['cn'][0]}) - " . $result['dn'], ENT_QUOTES, $GLOBALS['charset']);
						$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLResponseRow');
					}
				}
				
				if ($errorMessage != '') {
					$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLResponseHeader');
					$GLOBALS['ItemId'] = '';
					$GLOBALS['ItemText'] = htmlspecialchars($errorMessage, ENT_QUOTES, $GLOBALS['charset']);
					$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLResponseRow');
				}
				break;
			case 'refreshattachmentstatus':
				header('Content-type: text/xml');
				$className = str_replace('_Refresh', '', $_REQUEST['docType']);
				$plugin = new $className();
				$pluginCheck = $plugin->Check();
				$GLOBALS['ItemId'] = $className;
				if ($pluginCheck) {
					$GLOBALS['ItemText'] = '1';
				} else {
					$GLOBALS['ItemText'] = '0';
				}
				$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLResponseRow');
				break;
			case 'sendapprovalemail':
				header('Content-type: text/xml');
				$GLOBALS['ItemText'] = '0';
				// Update the article's status & Send email to the author
				$q = new AKB_QUESTION();
				if ($q->UpdateStatus($_REQUEST['questionIds'], $_REQUEST['status'], $_REQUEST['emailSubject'], $_REQUEST['emailBody'], $_REQUEST['skip'])) {
					$GLOBALS['ItemText'] = '1';
				}
				$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLResponseRow');
				break;
			case 'sortcategories':
				header('Content-type: text/xml');
				BuildCategoryOrders($_POST['CategoryList']);
				$GLOBALS['ItemText'] = GetLang('CategoryOrdersUpdated');
				$GLOBALS['ItemId'] = '1';
				
				$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLResponseRow');
				break;
		}
	}
	
		/**
		 * Automatically set the sortorder of the categories when they are dragged so they are displayed in the correct order
		 *
		 * @return void
		 **/
		function BuildCategoryOrders($list, $parent=0, $parents=array())
		{
			if(!is_array($list)) {
				return;
			}

			foreach($list as $order => $category) {
				$myParents = $parents;
				$myParents[] = $category['id'];
				$parentList = implode(",", $myParents);
				$catorder = $order+1;
				$SQL = "
					UPDATE ".$GLOBALS['tablePrefix']."categories
					SET
						parentid = '".$parent."',
						catorder = '".$catorder."' 
					WHERE
						categoryid = '".(int)$category['id']."'
				";
			$GLOBALS['AKB_DB']->Query($SQL);
				if(isset($category['children'])) {
					BuildCategoryOrders($category['children'], $category['id'], $myParents);
				}
			}
		}
	
	/**
	* results_cleanup
	* Remove whitespace before displaying - Makes parsing xml more predictable
	*
	* @param $str The string to cleanup
	* @return string The clean string
	*/
	function results_cleanup($str)
	{
		return str_replace(array("\t", "\n", "\r"), '', $str);
	}

	$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLResponseFooter');
	echo results_cleanup($output);
?>
